﻿// owner 蒋家伟

#include "WeakReference.h"

using namespace jsdk;

jsdk::WeakReference::~WeakReference()
{
    if (m_pProxy)
    {
        m_pProxy->reset();
    }
}

jsdk::WeakReference::WeakReference()
{
    if (m_pProxy == nullptr)
    {
        m_pProxy = new Proxy(this);
    }
}

jsdk::WeakReference::Proxy * jsdk::WeakReference::getProxy() const
{
    return m_pProxy;
}

jsdk::WeakReference::Proxy::Proxy(WeakReference* pWeakReference) : m_pWeakReference(pWeakReference)
{
}

jsdk::WeakReference::Proxy::~Proxy()
{
}

bool jsdk::WeakReference::Proxy::isValid() const
{
    return m_pWeakReference != nullptr;
}

void jsdk::WeakReference::Proxy::ref()
{
    m_count++;
}

void jsdk::WeakReference::Proxy::unRef()
{
    if (m_count == 1)
    {
        m_count = 0;
        if (!isValid())
        {
            // 如果没有对象引用，且代理的对象已经被析构了，那么删除当前的代理对象。
            delete this;
        }
    }
    else
    {
        m_count--;
    }
}

WeakReference * jsdk::WeakReference::Proxy::get() const
{
    return m_pWeakReference;
}

void jsdk::WeakReference::Proxy::reset()
{
    m_pWeakReference = nullptr;
    if (m_count == 0)
    {
        delete this;
    }
}
